package org.apache.struts2.plugin.json.writer;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import org.apache.struts2.plugin.json.Token;
import org.apache.struts2.plugin.json.model.JSONObject;
import org.apache.struts2.plugin.json.model.JSONString;
import org.apache.struts2.plugin.json.model.JSONValue;

/**
 * @author VERDOÏA Laurent <verdoialaurent@gmail.com>
 */
public class JSONObjectWriter extends AbstractJSONWriter<JSONObject> {

    public JSONObjectWriter(JSONObject content, OutputStream out) {
        super(content, out, Token.OBJECT_START, Token.OBJECT_END);
    }

    @Override
    public void writeContent() throws IOException {
        Map<JSONString, JSONValue> map = this.content.getData();
        if (map.isEmpty()) {
            return;
        }

        int max = map.size() - 1;
        int i = 0;

        for (Map.Entry<JSONString, JSONValue> entry : map.entrySet()) {
            AbstractJSONWriter key = new JSONStringWriter(entry.getKey(), out);
            AbstractJSONWriter value = JSONWriterFactory.create(entry.getValue(),
                    out);
            key.write();
            out.write(Token.OBJECT_ASSIGNEMENT.getBytes());
            value.write();
            if (i < max) {
                out.write(Token.COMMA.getBytes());
            }
            i++;
        }
    }
}
